package naga.x.platform2.channel.iapppay.support;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;

import org.slf4j.Logger;


public class RSA {
	
	public static final String ALGORITHM = "MD5WithRSA";
	private static final Logger LOG = IAppPayApi.LOG;
	
	public static String sign(String data, String privateKey) {
		return sign(data, IAppPayApi.DEFAULT_CHARSET, privateKey);
	}
	
	public static String sign(String data, String charset, String privateKey) {
		try {
			return sign(data.getBytes(charset), privateKey);
		} catch (Exception e) {
			LOG.error("[RSA SIGN ERR]DATA[" + data + "]CHARSET[" + charset + "]PRIKEY[" + privateKey + "]", e);
		}
		return null;
	}

	public static String sign(byte[] data, String privateKey) {
		try {
			PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey.getBytes(IAppPayApi.DEFAULT_CHARSET)));
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyFactory.generatePrivate(pkcs8);
			Signature signature = Signature.getInstance(ALGORITHM);
			signature.initSign(priKey);
			signature.update(data);
			byte[] base64 = Base64.getEncoder().encode(signature.sign());
			return new String(base64, IAppPayApi.DEFAULT_CHARSET);
		} catch (Exception e) {
			LOG.error("[RSA SIGN ERR]DATA[" + Arrays.toString(data) + "]PRIKEY[" + privateKey + "]", e);
		}
		return null;
	}
	
	public static boolean verify(String data, String sign, String publicKey) {
		return verify(data, IAppPayApi.DEFAULT_CHARSET, sign, publicKey);
	}
	
	public static boolean verify(String data, String charset, String sign, String publicKey) {
		try {
			return verify(data.getBytes(charset), sign, publicKey);
		} catch (Exception e) {
			LOG.error("[RSA VERIFY ERR]DATA[" + data + "]CHARSET[" + charset + "]SIGN[" + sign + "]PUBKEY[" + publicKey + "]", e);
		}
		return false;
	}
	
	public static boolean verify(byte[] data, String sign, String publicKey) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			byte[] pubKeyData = Base64.getDecoder().decode(publicKey.getBytes(IAppPayApi.DEFAULT_CHARSET));
			PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(pubKeyData));
			Signature signature = Signature.getInstance(ALGORITHM);
			signature.initVerify(pubKey);
			signature.update(data);
			return signature.verify(Base64.getDecoder().decode(sign.getBytes(IAppPayApi.DEFAULT_CHARSET)));
		} catch (Exception e) {
			LOG.error("[RSA VERIFY ERR]DATA[" + Arrays.toString(data) + "]SIGN[" + sign + "]PUBKEY[" + publicKey + "]", e);
		}
		return false;
	}
	
}
